<style>
.tree {
  /*margin-top: 42px;*/
  border: 1px solid #d7dde4;
  /* max-height: 600px; */
}

.prodShow {
  z-index: 10000;
}
</style>
<template>
<Row class="layout-content-body" id="print-pdf">
  <Form ref="editForm" :model="formItem" :label-width="100" :rules="ruleValidate">
    <Form-item label="名称" prop="Name">
      <Input v-model="formItem.Name" placeholder="请输入"></Input>
    </Form-item>
    <Form-item label="供应商" prop="CustName" required>
      <Input v-model="formItem.CustName" placeholder="请输入" @on-focus="custEdit"></Input>
    </Form-item>
    <Form-item label="金额" prop="Price">
      <Input v-model.number="formItem.Price" placeholder="请输入" disabled></Input>
    </Form-item>
    <Form-item label="优惠金额" prop="DiscountPrice" required>
      <Input v-model.number="formItem.DiscountPrice" placeholder="请输入"></Input>
    </Form-item>
    <Form-item label="优惠额" prop="Off">
      <Input v-model.number="formItem.Off" placeholder="请输入" disabled></Input>
    </Form-item>
    <Form-item label="说明" prop="Remark">
      <Input v-model="formItem.Remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入...">
      </Input>
    </Form-item>
    <FormItem label="付款方式">
      <Button-group>
        <Tooltip content="增加付款" placement="bottom-start" transfer>
          <Button type="ghost" @click="ReceivPlus">
            <Icon type="plus"></Icon>
          </Button>
        </Tooltip>
        <Tooltip content="减少付款" placement="bottom-start" transfer>
          <Button type="ghost" @click="ReceivMinus">
            <Icon type="minus"></Icon>
          </Button>
        </Tooltip>
      </Button-group>
    </FormItem>
    <FormItem v-for="(item, index) in recive" :key="item.Seq" :label="'第'+item.Seq +'次付款'" required>
      <Row>
        <Col span="2" style="text-align: right">付款时间：</Col>
        <Col span="4">
        <DatePicker v-model="item.Date" format="yyyy年MM月dd日" type="date" placeholder="Select date" style="width: 200px"></DatePicker>
        </Col>
        <Col span="2" style="text-align: right">应付金额：</Col>
        <Col span="4">
        <Slider v-model="item.Percent" 
        :tip-format="formatPercent"  :show-tip="PercentShow" ></Slider>
        </Col>
        <Col span="2" style="text-align: right">说明：</Col>
        <Col span="8">
        <Input v-model="item.Remark" placeholder="请输入"></Input>
        </Col>
      </Row>
    </FormItem>
    <Form-item>
      <Button type="primary" @click="handleSubmit('editForm')">提交</Button>
      <Button type="ghost" @click="handleReset('editForm')" style="margin-left: 8px">取消</Button>
      <Button type="ghost" @click="printContent" style="margin-left: 8px">打印</Button>
    </Form-item>
  </Form>
  <dtable 
    :columnsList="columns" 
    v-model="dataAll" 
    :totals="total" 
    add check op delCheck 
    :hover-show="true" 
    :edit-incell="true" 
    @add="salesAdd" @input="input" @del="salesDel" @edit="salesEdit" 
    :loading="loading" :pageS="100">
  </dtable>
  <Modal title="供应商" v-model="custShow" @on-ok="custOk" width=80>
    <cust @handelSelect="custSelect"></cust>
  </Modal>
  <Modal title="产品" v-model="prodShow" @on-ok="prodOk" width=80 class-name="prodShow">
    <prod @handelSelect="prodSelect"></prod>
  </Modal>
  <Modal title="订单明细" v-model="salesShow" @on-ok="salesOk">
    <Form ref="formSales" :model="formSales" :label-width="80">
      <Form-item label="产品" prop="Name">
        <Input v-model="formSales.Name" placeholder="请输入" :disabled="!salesAd" @on-focus="prodEdit"></Input>
      </Form-item>
      <Form-item label="数量" prop="Count">
        <InputNumber :min="1" v-model.number="formSales.Count"></InputNumber>
      </Form-item>
      <Form-item label="单价" prop="Price">
        <Input v-model.number="formSales.Price" disabled>
        </Input>
      </Form-item>
      <Form-item label="优惠价" prop="DiscountPrice">
        <Input v-model.number="formSales.DiscountPrice">
        </Input>
      </Form-item>
      <Form-item label="说明" prop="Remark">
        <Input v-model="formSales.Remark">
        </Input>
      </Form-item>
    </Form>
  </Modal>
</Row>
</template>

<script>
import {
  getData
} from '@/common/utils'
import {
   currency
} from '@/common/filter'
import dtable from '@/components/table/etable.vue' //
// import cust from '@/views/busy/cust'
import cust from '@/views/busy/supplier'
import prod from '@/views/busy/prod'
var list = []
var item = {}
export default {
  data() {
    return {
      loading: false, //数据刷新遮罩层
      columns: [
        //多选框
        {
          title: '名称',
          key: 'Name',
          sortable: true
        },
        {
          title: '型号',
          key: 'Model',
          sortable: true
        },
        {
          title: '价格',
          key: 'Price',
          sortable: true,
          render: (h, params) => {
            return h('div', [
              h('strong', currency(params.row.Price,"￥"))
            ]);
          }
        },
        {
          title: '优惠价格',
          key: 'DiscountPrice',
          sortable: true,
          editable: true,
          render: (h, params) => {
            return h('div', [
              h('strong', currency(params.row.DiscountPrice,"￥"))
            ]);
          }
        },
        {
          title: '数量',
          key: 'Count',
          sortable: true,
          editable: true
        },
        {
          title: '金额',
          key: 'Money',
          sortable: true,
          render: (h, params) => {
            return h('div', [
              h('strong', currency(params.row.Money,"￥"))
            ]);
          }
        },
        {
          title: '说明',
          key: 'Remark',
          sortable: true,
        },
      ], //表格样式
      summary: {
        Name: '合计',
        Money: 0
      },
      dataAll: [], //表格数据来源含合计
      datas: [], //表格数据来源
      formItem: {
        Id: '',
        Name: '',
        CustName: '',
        Remark: '',
        Price: 0,
        Receiv: [],
        Sales: [],
        ReceivTime: 0,
        DiscountPrice: 0,
        Off: 0
      }, //数据编辑表单
      formSales: {
        Id: '',
        Name: '',
        Count: 1,
        Remark: '',
        Price: 0,
        DiscountPrice: 0,
        Off: 0
      },
      ruleValidate: {
        Name: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        }],
      }, //数据编辑表单验证规则
      addid: true, //true为修改模式，false为添加模式
      salesAd: false,
      custShow: false,
      prodShow: false,
      salesShow: false,
      recive: [],
      PercentShow:'always',
      cust: [],
      prod: [],
      total: 0,
      orderData: this.$route.params.orderData,
    }
  },
  components: {
    dtable,
    cust,
    prod,
  },
  computed: {},
  props: {

  },
  watch: {},
  methods: {
    getSummaryMoney() {
      let sum = 0
      if (this.datas) {
        for (let m in this.datas) {
          sum = sum + this.datas[m].Money
        }
      }
      return sum
    },
    getall() {
      if (!this.orderData ) {
        this.$router.push({
          name: '采购订单'
        })
        return
      }
      this.loading = true
      this.dataAll.pop()
      if (this.orderData.edit) {
        this.formItem = getData(this.orderData.order)
        this.$api.getSales(this.orderData.order.Id).then(res => {
          if (!res.error) {
            this.datas = res.Data.sales
            this.recive = getData(res.Data.receiv)
            this.ReceivePercent()
            if (this.datas) {
              for (let e in this.datas) {
                this.datas[e].Money = this.datas[e].DiscountPrice * this.datas[e].Count
              }
              this.total = (this.datas).length
            }
            this.dataAll = getData(this.datas)
            this.formItem.Sales = getData(this.datas)
            this.summary.Money = this.getSummaryMoney()
            this.dataAll.push(this.summary)
            // this.loading = false; 
          } else {
            this.$Message.error(res.message)
          }
        })

        this.loading = false;
      } else {
        if (this.orderData.temp) {
          this.$api.getTempitem(this.orderData.temp).then(res => {
            if (!res.error) {
              this.datas = getData(res.Data)
              if (this.datas) {
                for (let e in this.datas) {
                  this.datas[e].Money = this.datas[e].Price * this.datas[e].Count
                  this.datas[e].DiscountPrice = this.datas[e].Price
                }
                this.total = (this.datas).length
                this.dataAll = getData(this.datas)
              } else {
                this.dataAll = []
                this.datas = []
                this.total = (this.dataAll).length
              }
              this.summary.Money = this.getSummaryMoney()
              this.dataAll.push(this.summary)
              this.ReceivPlus()
              // this.loading = false
            } else {
              this.$Message.error(res.message)
            }
          })
        }
        // this.summary.Money = this.getSummaryMoney()
        // this.dataAll.push(this.summary)
        this.loading = false;
      }
    },

    salesEdit(index) {
      this.salesAd = false
      this.formSales = index
      this.salesShow = true
    },
    salesAdd() {
      this.salesAd = true
      this.$refs['formSales'].resetFields()
      this.salesShow = true
    },
    salesOk() {
      this.formSales.Money = this.formSales.DiscountPrice * this.formSales.Count
      this.dataAll = []
      item = getData(this.formSales)
      if (this.salesAd) {

        this.datas = this.findProdAdd(this.datas, item)
        // this.dataAll=this.findProdAdd(this.dataAll,item)
      } else {
        this.datas = this.findProdEdit(this.datas, item)
      }
      this.dataAll = getData(this.datas)
      this.summary.Money = this.getSummaryMoney()
      this.dataAll.push(this.summary)
      this.formItem.Price = this.summary.Money
      this.formItem.DiscountPrice = this.summary.Money
      this.formItem.Off = this.formItem.Price - this.formItem.DiscountPrice
      this.formItem.Sales = this.datas
      this.salesShow = false
    },
    salesDel(row) {
      this.$api.deleteProdType(row).then(res => {
        if (!res.error) {
          this.getall()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      })
    },
    salesDelCheck(row) {

    },
    input(data) {
      // console.log(data)
      // this.dataAll = []
      this.datas = getData(data)
      this.datas.pop()
      this.datas = this.inputEdit(this.datas)
      this.dataAll = getData(this.datas)
      this.summary.Money = this.getSummaryMoney()
      this.dataAll.push(this.summary)
      this.formItem.Price = this.summary.Money
      this.formItem.DiscountPrice = this.summary.Money
      this.formItem.Off = this.formItem.Price - this.formItem.DiscountPrice
      this.formItem.Sales = this.datas
      this.salesShow = false
    },
    custEdit() {
      this.custShow = true
    },
    custOk() {
      if (this.cust.length > 1) {
        this.$Message.error('客户只能选择一个');
      } else {
        console.log(this.cust[0])
        this.formItem.CustId = this.cust[0].Id
        this.formItem.CustName = this.cust[0].Name
        this.formItem.Contact=this.cust[0].CustName
        this.formItem.Address=this.cust[0].Address
        this.formItem.Phone=this.cust[0].Phone
        console.log(this.formItem)
      }
    },
    custSelect(selection) {
      // console.log(selection[0])
      if (selection.length > 1) {
        this.$Message.error('客户只能选择一个');
      }
      this.cust = selection
    },
    prodEdit() {
      this.prodShow = true
    },
    prodOk() {
      if (this.prod.length > 1) {
        this.$Message.error('产品只能选择一个');
      } else {
        this.formSales.ProdId = this.prod[0].Id
        this.formSales.Price = this.prod[0].Price
        this.formSales.DiscountPrice = this.prod[0].Price
        this.formSales.Name = this.prod[0].Name
        this.formSales.Cost = this.prod[0].Cost
        this.formSales.Model = this.prod[0].Model
        this.formSales.Spec = this.prod[0].Spec
        this.formSales.Off = this.formSales.Price - this.formSales.DiscountPrice
      }
    },
    prodSelect(selection) {
      // console.log(selection[0])
      if (selection.length > 1) {
        this.$Message.error('产品只能选择一个');
      }
      this.prod = selection
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid && this.ReceiveOK()) {
          this.formItem.Receiv = getData(this.recive)
          if (!this.orderData.edit) {
            this.$api.addBuy(this.formItem).then(res => {
              if (!res.error) {
                this.$Message.success(res.message)
                this.$router.push({
                  name: '采购订单'
                })
              } else {
                this.$Message.error(res.message, 4)
              }
            })
          } else {
            console.log(this.formItem)
            this.$api.updateOrder(this.formItem).then(res => {
              if (!res.error) {
                this.$Message.success(res.message)
                this.$router.push({
                  name: '销售订单'
                })
              } else {
                this.$Message.error(res.message, 4)
              }
            })
          }
        } else {
          this.$Message.error('表单验证失败或付款金额与总额不符!')
        }
      })
    },
    handleReset(name) {
      this.$router.push({
        name: '销售订单'
      })
    },
    findProdAdd(array, x) {
      var len = array.length,
        pos = 0;
      while (pos < len) {
        if (array[pos].ProdId === x.ProdId) { //未找到就退出循环完成搜索
          array[pos].Count = array[pos].Count + x.Count
          array[pos].Money = array[pos].DiscountPrice * array[pos].Count
          break
        }
        pos += 1; //并从下个位置开始搜索
      }
      if (pos === len) {
        array.push(x)
      }
      return array
    },
    findProdEdit(array, x) {
      var len = array.length,
        pos = 0;
      while (pos < len) {
        if (array[pos].ProdId === x.ProdId) { //未找到就退出循环完成搜索
          array[pos].Count = x.Count
          array[pos].Money = array[pos].DiscountPrice * array[pos].Count
          break
        }
        pos += 1; //并从下个位置开始搜索
      }
      return array
    },
    inputEdit(array) {
      var len = array.length,
        pos = 0;
      while (pos < len) {
        array[pos].Count = Number(array[pos].Count)
        array[pos].Money = array[pos].DiscountPrice * array[pos].Count
        pos += 1; //并从下个位置开始搜索
      }
      return array
    },
    getindex(data) {
      return data + 1
    },
    ReceivPlus() {
      let rc = {
        Seq: 1,
        Date: '',
        Money: 0,
        Remark: ''
      }
      let len = this.recive.length
      if (len > 0) {
        rc.Seq = this.recive[len - 1].Seq + 1
      }
      this.recive.push(rc)
    },
    ReceivMinus() {
      this.recive.pop()
    },
    ReceiveOK() {
      let ok = false,
       len = this.recive.length,
        pos = 0,sum=this.ReceiveSum()
      while (pos < len) {
       this.recive[pos].Money =  this.formItem.DiscountPrice*this.recive[pos].Percent/100
        pos += 1; //并从下个位置开始搜索
      }
      console.log(sum)
      console.log(this.formItem)
       console.log(this.recive)
      if (100 === sum) {
        ok = true
      }
      return ok
    },
    ReceiveSum() {
      let len = this.recive.length,
        pos = 0,sum=0
      while (pos < len) {
        sum = sum + this.recive[pos].Percent
        pos += 1; //并从下个位置开始搜索
      }
      return sum
    },
    ReceivePercent() {
      let len = this.recive.length,
        pos = 0
      let sum = this.formItem.DiscountPrice
      while (pos < len) {
        this.recive[pos].Percent = this.recive[pos].Money/sum*100
        pos += 1; //并从下个位置开始搜索
      }
      return 
    },
    formatPercent (val) {
      return '付款比例: ' + val + '%;'+'付款金额：'+this.formItem.DiscountPrice*val/100
    },
     printContent(e){  
               let subOutputRankPrint = document.getElementById('print-pdf');  
               console.log(subOutputRankPrint.innerHTML);  
               let newContent =subOutputRankPrint.innerHTML;  
               let oldContent = document.body.innerHTML;  
               document.body.innerHTML = newContent;  
               window.print();  
               window.location.reload();  
               document.body.innerHTML = oldContent;  
               return false;  
           },  

  },
  mounted() {
    this.getall()
    // console.log(this.formItem.Receiv)
  }
}
</script>
